package com.yc.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yc.bean.Cartinfo;
import com.yc.bean.User;
import com.yc.biz.CartinfoBiz;
import com.yc.biz.UserBiz;
import com.yc.biz.impl.CartinfoBizImpl;
import com.yc.biz.impl.UserBizImp1;
import com.yc.dao.DBHelper;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
	UserBiz ub = new UserBizImp1();
	CartinfoBiz cb=new CartinfoBizImpl();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		PrintWriter out = resp.getWriter();

		// 获取参数
		String op = req.getParameter("op");
		if ("reg".equals(op)) {
			reg(req, resp, out);
		}else if ("login".equals(op)) {
			login(req, resp, out);
		}else if ("user_modify".equals(op)) {
			user_modify(req, resp, out);
		}

	}
	
	

	private void user_modify(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
		int uid = 0;
		String uname = null;
		String pwd = null;
		String tel = null;
		String paypwd=null;
		try {
			uid = Integer.parseInt(req.getParameter("uid"));
			uname = req.getParameter("uname");
			pwd = req.getParameter("pwd");
			paypwd=req.getParameter("paypwd");
			tel = req.getParameter("tel");
		} catch (Exception e) {
//			e.printStackTrace();
			out.print(-1);
		}
		int result = ub.modify_person(uid,uname,pwd,paypwd,tel);
		if(result>0){
			User user = ub.login(uname, pwd);
			req.getSession().setAttribute("user", user);
		}
		out.print( result );
	}

	// 注册
	private void reg(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
		String uname = req.getParameter("uname");
		String pwd = req.getParameter("pwd");
		String tel = req.getParameter("tel");

		int result = ub.reg(uname, pwd,tel);
		if(result>0){
			out.print(1);
			req.getSession().setAttribute("uname", uname);
		}else{
			out.print(0);
		}
		
	}

	// 登录
	private void login(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
		String uname = req.getParameter("uname");
		String pwd = req.getParameter("pwd");
		User user = ub.login(uname, pwd);
		
		if (user == null) {
			out.print(0);
		} else {
			// 存session
			req.getSession().setAttribute("user", user);
			req.getSession().setAttribute("uid", user.getUid());
			
			//登录成功后查询购物车数量 并且存session
			int cartNum=cb.findCartNum(user.getUid());
			req.getSession().setAttribute("cartNum", cartNum);
			out.print(1);
		}
	}
}
